//
//  KLSingleLockInfoTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/5/20.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLSingleLockInfoTableViewController.h"
#import "KLHttpAPI.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "Masonry.h"
#import "HemaFunction.h"
#import "JRToast.h"
//#import "KLSendChildKeyViewController.h"
#import <objc/runtime.h>
#import "BuleFuction.h"
#import "IdentifierValidator.h"
#import "KLDelegateCommondTableViewController.h"
#import "KLOpenLockHistoryTableViewController.h"
#import "KLSecondUserTableViewController.h"
#import "UIAlertView+Blocks.h"
#import "KLNewSendKeyVC.h"

@interface KLSingleLockInfoTableViewController ()<UIAlertViewDelegate,UIActionSheetDelegate>
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *addressLabel;
@property (nonatomic,strong) UIButton *removeMasterPower;//放弃锁主权限
@end

@implementation KLSingleLockInfoTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delaysContentTouches =NO;
    //初始化头视图
    [self headViewSet];
    //初始化导航栏
    [self naveSet];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doBack:) name:@"backToLockList" object:nil];
    NSLog(@"当前的锁信息为:%@",self.currentLockInfoDic);
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.isFirstMaster){
        return 9;
    }else
        return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"singleLock"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.section == 0){
        cell.textLabel.text = @"锁主校时";
    }else if (indexPath.section == 1){
        cell.textLabel.text = @"设置黑名单";
    }else if (indexPath.section == 2){
        cell.textLabel.text = @"取消黑名单";
    }else if (indexPath.section == 3){
        cell.textLabel.text = @"读取锁信息";
    }else if (indexPath.section == 4){
        cell.textLabel.text = @"更换锁芯";
        if (!_isFirstMaster) {
            cell.textLabel.text = @"历史记录";
        }
    }else if (indexPath.section == 5){
        cell.textLabel.text = @"历史记录";
        if (!_isFirstMaster) {
            cell.textLabel.text = @"委托管理";
        }
    }else if (indexPath.section == 6){
        cell.textLabel.text = @"委托管理";
    }else if (indexPath.section == 7) {
        cell.textLabel.text = @"授权管理";
    }else if (indexPath.section == 8) {
        cell.textLabel.text = @"设置开锁密码";
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请离锁30cm以内对该锁校时" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 13;
        [alert show];
    }else if (indexPath.section == 1){
        //设置黑名单
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请离锁30cm以内设置黑名单" message:@"输入黑名单用户的手机号" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.tag = 14;
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField *tf=[alert textFieldAtIndex:0];
        tf.keyboardType = UIKeyboardTypeNumberPad;
        [alert show];
    }else if (indexPath.section == 2){
        //取消黑名单
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请离锁30cm以内取消黑名单" message:@"输入黑名单用户的手机号" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.tag = 15;
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField *tf=[alert textFieldAtIndex:0];
        tf.keyboardType = UIKeyboardTypeNumberPad;
        [alert show];
    }else if (indexPath.section == 3){
        //读取锁信息
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请离锁30cm以内读取锁信息" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 17;
        [alert show];
    }else if (indexPath.section == 4){
        // 判断一级锁主
        if (_isFirstMaster) {
            // 新增需求
            NSLog(@"跟换锁芯相关操作");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请离锁30cm以内跟换锁芯" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 18;
            [alert show];
        }else {
            //查询开锁历史记录
            KLOpenLockHistoryTableViewController *openLockHistoryVC = [[KLOpenLockHistoryTableViewController alloc]init];
            openLockHistoryVC.currentLockInfo = self.currentLockInfoDic;
            [self.navigationController pushViewController:openLockHistoryVC animated:YES];
        }

    } else if (indexPath.section == 5){
        if (_isFirstMaster) {
            //查询开锁历史记录
            KLOpenLockHistoryTableViewController *openLockHistoryVC = [[KLOpenLockHistoryTableViewController alloc]init];
            openLockHistoryVC.currentLockInfo = self.currentLockInfoDic;
            [self.navigationController pushViewController:openLockHistoryVC animated:YES];
        }else {
            //委托管理
            KLDelegateCommondTableViewController *delegateCommondVC = [[KLDelegateCommondTableViewController alloc]init];
            delegateCommondVC.currentLockInfo = self.currentLockInfoDic;
            delegateCommondVC.isFirstMaster = self.isFirstMaster;
            [self.navigationController pushViewController:delegateCommondVC animated:YES];
        }
        
        //委托管理
    }else if (indexPath.section == 6){
        //委托管理
        KLDelegateCommondTableViewController *delegateCommondVC = [[KLDelegateCommondTableViewController alloc]init];
        delegateCommondVC.currentLockInfo = self.currentLockInfoDic;
        delegateCommondVC.isFirstMaster = self.isFirstMaster;
        [self.navigationController pushViewController:delegateCommondVC animated:YES];
    }else if (indexPath.section == 7) {
        //授权用户列表
        KLSecondUserTableViewController *secondUser = [[KLSecondUserTableViewController alloc]init];
        secondUser.currentLockDic = self.currentLockInfoDic;
        [self.navigationController pushViewController:secondUser animated:YES];
    }else if (indexPath.section == 8) {
        // 设置开锁密码:分开写
        [self setupUnlockingPwdAlertController];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    /*
    if(section == 4)
        return 20;
    else
        return 2;
     */
    if ((section == 5) && _isFirstMaster) { // 一级锁主
        return 20;
    }else if((section == 4) && !_isFirstMaster) { // 二级锁主
        return 20;
    }else {
        return 2;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 20)];
    header.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    return header;
}

#pragma mark -界面设置
//初始化导航栏
-(void)naveSet{
    self.title = @"锁详情";
    self.view.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    if(self.isFirstMaster){
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 70)];
        self.tableView.tableFooterView = footerView;
        self.removeMasterPower = [[UIButton alloc]initWithFrame:CGRectMake(50, 25, UI_View_Width-100, 45)];
        [self.removeMasterPower setBackgroundImage:[UIImage imageNamed:@"删除锁主权限"] forState:UIControlStateNormal];
        [self.removeMasterPower setTitle:@"放弃锁主权限" forState:UIControlStateNormal];
        [self.removeMasterPower setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        self.removeMasterPower.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
        self.removeMasterPower.layer.masksToBounds = YES;
        self.removeMasterPower.layer.cornerRadius = 8;
        [self.removeMasterPower addTarget:self action:@selector(giveUpMasterPower:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:self.removeMasterPower];
    }else{
        self.tableView.tableFooterView = [[UIView alloc]init];
    }
    
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

//初始化头视图
-(void)headViewSet{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 120)];
    headView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headView;
    //锁图片
    UIImageView *lockImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"deviceicon"]];
    [headView addSubview:lockImage];
    [lockImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headView).with.offset(0);
        make.left.mas_equalTo(13);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(55);
    }];
    UILabel *title1 = [[UILabel alloc]init];
    title1.text = @"锁名: ";
    title1.textColor = RGB_UI_COLOR(70, 70, 70);
    title1.alpha = 0.7;
    title1.textAlignment = NSTextAlignmentLeft;
    title1.font = [UIFont systemFontOfSize:14];
    [headView addSubview:title1];
    [title1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(75);
    }];
    //锁原始名
    UILabel *unameLabel = [[UILabel alloc]init];
    NSString *lockUname = [NSString stringWithFormat:@"%@",[self.currentLockInfoDic objectForKey:@"uname"]];
    unameLabel.text = lockUname;
    unameLabel.backgroundColor = RGB_UI_COLOR(255, 211, 155);
    unameLabel.textAlignment = NSTextAlignmentLeft;
    unameLabel.font = [UIFont systemFontOfSize:14];
    [headView addSubview:unameLabel];
    [unameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(115);
        make.right.mas_equalTo(-35);
    }];
    
    UILabel *title2 = [[UILabel alloc]init];
    title2.textColor = RGB_UI_COLOR(70, 70, 70);
    title2.alpha = 0.7;
    title2.text = @"别名: ";
    title2.textAlignment = NSTextAlignmentLeft;
    title2.font = [UIFont systemFontOfSize:14];
    [headView addSubview:title2];
    [title2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.left.mas_equalTo(75);
    }];
    //锁别名
    self.nameLabel = [[UILabel alloc]init];
    NSString *lockName = [NSString stringWithFormat:@"%@",[self.currentLockInfoDic objectForKey:@"name"]];
    self.nameLabel.text = lockName;
    self.nameLabel.numberOfLines = 1;
    self.nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    self.nameLabel.backgroundColor = RGB_UI_COLOR(255, 211, 155);
    self.nameLabel.textAlignment = NSTextAlignmentLeft;
    self.nameLabel.font = [UIFont systemFontOfSize:14];
    [headView addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.left.mas_equalTo(115);
        make.right.mas_equalTo(-35);
    }];
    
    //编辑别名按钮
    if(self.isFirstMaster){
        UIButton *editNameBtn = [[UIButton alloc]init];
        [editNameBtn setBackgroundImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
        [editNameBtn addTarget:self action:@selector(eidtName:) forControlEvents:UIControlEventTouchUpInside];
        [headView addSubview:editNameBtn];
        [editNameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.nameLabel).with.offset(0);
            make.right.equalTo(self.nameLabel).with.offset(25);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
        }];
    }
    
    UILabel *title3 = [[UILabel alloc]init];
    title3.textColor = RGB_UI_COLOR(70, 70, 70);
    title3.alpha = 0.7;
    title3.text = @"地址: ";
    title3.textAlignment = NSTextAlignmentLeft;
    title3.font = [UIFont systemFontOfSize:14];
    [headView addSubview:title3];
    [title3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(80);
        make.left.mas_equalTo(75);
    }];
    //锁地址
    self.addressLabel = [[UILabel alloc]init];
    NSString *address_default = [NSString stringWithFormat:@"%@",[self.currentLockInfoDic objectForKey:@"address"]];
    self.addressLabel.text = address_default;
    self.addressLabel.backgroundColor = RGB_UI_COLOR(255, 211, 155);
    self.addressLabel.numberOfLines = 2;
    self.addressLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    self.addressLabel.textAlignment = NSTextAlignmentLeft;
    self.addressLabel.font = [UIFont systemFontOfSize:14];
    [headView addSubview:self.addressLabel];
    [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(80);
        make.left.mas_equalTo(115);
        make.right.mas_equalTo(-35);
    }];
    
    //编辑地址按钮
    if(self.isFirstMaster){
        UIButton *addressBtn = [[UIButton alloc]init];
        [addressBtn setBackgroundImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
        [addressBtn addTarget:self action:@selector(eidtAddress:) forControlEvents:UIControlEventTouchUpInside];
        [headView addSubview:addressBtn];
        [addressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.addressLabel).with.offset(0);
            make.right.equalTo(self.addressLabel).with.offset(25);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
        }];
    }
    
    //分发子钥匙按钮
    UIButton *sendChildKeyBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 30)];
    [sendChildKeyBtn setTitle:@"分发钥匙" forState:UIControlStateNormal];
    [sendChildKeyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendChildKeyBtn addTarget:self action:@selector(sendChildKey:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:sendChildKeyBtn];
}

#pragma mark -分发子钥匙
-(void)sendChildKey:(id)sender{
//    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择要分发的钥匙种类" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"平等钥匙",@"临时钥匙", nil];
//    sheet.tag = 21;
//    sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
//    [sheet showInView:self.view];
    KLNewSendKeyVC *newSendKeyVC = [[KLNewSendKeyVC alloc]init];
    newSendKeyVC.lockDetailDic = self.currentLockInfoDic;
    [self.navigationController pushViewController:newSendKeyVC animated:YES];
}

#pragma mark -编辑别名
-(void)eidtName:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"锁别名编辑" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.tag = 11;
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];
}

#pragma mark - 编辑地址
-(void)eidtAddress:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"锁地址编辑" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.tag = 16;
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];
}

#pragma mark -alertView的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //alertView的tag值以1开头
    if(alertView.tag == 11){//修改别名
        UITextField *tf=[alertView textFieldAtIndex:0];
        NSString *tf_text = tf.text;
        if(buttonIndex == 1 && ![HemaFunction xfunc_check_strEmpty:tf_text]){
            [KLHttpAPI convertLockUnameToNameWithLockID:[self.currentLockInfoDic objectForKey:@"id"]
                                                  alias:tf.text
                                      completionHandler:^(NSDictionary *responseDic) {
                                          NSString *isSuccess = [responseDic objectForKey:@"success"];
                                          if(isSuccess.integerValue){
                                              [JRToast showWithText:@"修改成功"];
                                              self.nameLabel.text = [NSString stringWithFormat:@"%@",tf_text];
                                              [[NSNotificationCenter defaultCenter] postNotificationName:@"scanSuccess" object:nil userInfo:nil];
                                          }
                                      } errorHandler:^(NSString *error) {
                                      }];
        }
    }
    else if (alertView.tag == 12){//删除临时钥匙
        if(buttonIndex == 1){
            [KLHttpAPI removeAllTemporaryKeyWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] lock_id:[self.currentLockInfoDic objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"删除全部临时钥匙的返回数据:%@",operation.responseString);
                NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                NSDictionary *dic = [operation.responseJSON objectForKey:@"infor"];
                NSString *seriNumber = [dic objectForKey:@"serinumber"];
                if(isSuccess.integerValue == 1){
                    [KLHelp showTextHUDforView:self.view text:@"删除成功"];
                    NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:self.currentLockInfoDic];
                    [newDic removeObjectForKey:@"serinumber"];
                    [newDic setObject:seriNumber forKey:@"serinumber"];
                    self.currentLockInfoDic = newDic;
                }else{
                    [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
            }];
        }
    }
    else if(alertView.tag == 13){//校时
        if(buttonIndex == 1){
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSString stringWithFormat:@"1"] forKey:@"commondType"];
            [dic setObject:self.currentLockInfoDic forKey:@"currentLockInfo"];
            [dic setObject:self.view forKey:@"lockDetailView"];
            //给主界面发通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"checkOutTime" object:nil userInfo:dic];
        }
    }
    else if (alertView.tag == 14){//设置黑名单
        UITextField *tf=[alertView textFieldAtIndex:0];
//        tf.keyboardType = UIKeyboardTypeNumberPad;
        NSString *tf_text = tf.text;
        if(buttonIndex == 1){
            if(![IdentifierValidator isValid:IdentifierTypePhone value:tf_text]){
                [JRToast showWithText:@"手机号格式有误"];
            }else if([tf_text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]]){
                [JRToast showWithText:@"不能将自己设为黑名单"];
            }else{
                [KLHttpAPI phoneNumberChangeToUserIDWithPhoneNUm:tf_text completionHandler:^(MKNetworkOperation *operation) {
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                        [dic setObject:[NSString stringWithFormat:@"2"] forKey:@"commondType"];
                        [dic setObject:self.currentLockInfoDic forKey:@"currentLockInfo"];
                        [dic setObject:[operation.responseJSON objectForKey:@"infor"] forKey:@"blackPhone"];
                        [dic setObject:self.view forKey:@"lockDetailView"];
                        //给主界面发通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"settingBlackList" object:nil userInfo:dic];
                    }else{
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    }
                } errorHandler:^(NSString *error) {
                    [KLHelp showTextHUDforView:self.view text:error];
                }];
            }
        }
    }
    else if (alertView.tag == 15){//设置取消黑名单
        UITextField *tf=[alertView textFieldAtIndex:0];
//        tf.keyboardType = UIKeyboardTypeNumberPad;
        NSString *tf_text = tf.text;
        if(buttonIndex == 1){
            if(![IdentifierValidator isValid:IdentifierTypePhone value:tf_text]){
                [JRToast showWithText:@"手机号格式有误"];
            }else if([tf_text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]]){
                [JRToast showWithText:@"不能取消自己的黑名单"];
            }else{
                [KLHttpAPI phoneNumberChangeToUserIDWithPhoneNUm:tf_text completionHandler:^(MKNetworkOperation *operation) {
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                        [dic setObject:[NSString stringWithFormat:@"3"] forKey:@"commondType"];
                        [dic setObject:self.currentLockInfoDic forKey:@"currentLockInfo"];
                        [dic setObject:tf_text forKey:@"blackPhone"];
                        [dic setObject:self.view forKey:@"lockDetailView"];
                        //给主界面发通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelBlackList" object:nil userInfo:dic];
                    }else{
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    }
                } errorHandler:^(NSString *error) {
                    [KLHelp showTextHUDforView:self.view text:error];
                }];
            }
        }
    }
    else if (alertView.tag == 16){//编辑地址
        UITextField *tf=[alertView textFieldAtIndex:0];
        NSString *tf_text = tf.text;
        if(buttonIndex == 1 && ![HemaFunction xfunc_check_strEmpty:tf_text]){
            [KLHttpAPI editLockAddressWithLockID:[self.currentLockInfoDic objectForKey:@"id"] address:tf.text completionHandler:^(NSDictionary *responseDic) {
                NSString *isSuccess = [responseDic objectForKey:@"success"];
                if(isSuccess.integerValue){
                    [JRToast showWithText:@"修改成功"];
                    self.addressLabel.text = [NSString stringWithFormat:@"%@",tf_text];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"scanSuccess" object:nil userInfo:nil];
                }
            } errorHandler:^(NSString *error) {
            }];
        }
    }
    else if (alertView.tag == 17){//读取锁信息
        if(buttonIndex == 1){
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSString stringWithFormat:@"4"] forKey:@"commondType"];
            [dic setObject:self.currentLockInfoDic forKey:@"currentLockInfo"];
            [dic setObject:self.view forKey:@"lockDetailView"];
            //给主界面发通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"readLockMessage" object:nil userInfo:dic];
        }
    }
    else if (alertView.tag == 18) {
        if (buttonIndex == 1) {  // 更换锁芯
            NSMutableDictionary *changeKeyCoreDic = [NSMutableDictionary dictionary];
            [changeKeyCoreDic setObject:[NSString stringWithFormat:@"5"] forKey:@"commondType"];
            [changeKeyCoreDic setObject:self.currentLockInfoDic forKey:@"currentLockInfo"];
            [changeKeyCoreDic setObject:self.view forKey:@"lockDetailView"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeKeyCore" object:nil userInfo:changeKeyCoreDic];
        }
    }
}

#pragma mark -actionSheet的代理方法
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    //actionSheet的tag值以2开头
    if(actionSheet.tag == 21){//发子钥匙时选择发平等钥匙还是临时钥匙
//        KLSendChildKeyViewController *send_child_keyVC = [[KLSendChildKeyViewController alloc]init];
//        send_child_keyVC.currentLockDic = self.currentLockInfoDic;
        
    }else if (actionSheet.tag == 31){
        if(buttonIndex == 0){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"是否确定放弃锁主权限" message:@"放弃之后您可以在该锁没有新主人之前重新扫描添加" cancelButtonItem:[RIButtonItem itemWithLabel:@"确定放弃" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI requestGiveUpMasterPowerWithLockID:[self.currentLockInfoDic objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
                    NSLog(@"放弃锁主权限:%@",operation.responseString);
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"scanSuccess" object:nil userInfo:nil];
//                        [self.navigationController popViewControllerAnimated:YES];
                    }
                } errorHandler:^(NSString *error) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                }];
            }] otherButtonItems:[RIButtonItem itemWithLabel:@"我再想想" action:nil], nil];
            [alert show];
        }
    }
}

#pragma mark - 放弃锁主权限
-(void)giveUpMasterPower:(UIButton *)sender{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"放弃锁主将导致所有子钥匙及二级锁主全部失效" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"放弃" otherButtonTitles:@"取消", nil];
    sheet.tag = 31;
    
    [sheet showInView:self.view];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark 设置 开锁密码 弹框操作
- (void)setupUnlockingPwdAlertController {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"请离锁30cm内设置开锁密码" message:@"设置开锁密码" preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
       textField.placeholder = @"请输入开锁密码";
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

        NSArray *textfields = alertC.textFields;
        UITextField *tf = [textfields firstObject];
       // 判断字符串长度为6个字节
        if (tf.text.length != 6) {
            [JRToast showWithText:@"设置密码长度不正确" duration:1.0];
            return ;
        }
        
        NSMutableDictionary *unlockingDic = [NSMutableDictionary dictionary];
        [unlockingDic setObject:@"6" forKey:@"commondType"]; // 用于在主界面进行判断
        [unlockingDic setObject:tf.text forKey:@"unlockingPassword"]; // 设置密码
        [unlockingDic setObject:self.currentLockInfoDic forKey:@"currentLockInfo"];
        [unlockingDic setObject:self.view forKey:@"lockDetailView"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"unlockingInfoNotification" object:nil userInfo:unlockingDic];
        
    }];
    
    
    [alertC addAction:cancel];
    [alertC addAction:sure];
    [self presentViewController:alertC animated:YES completion:nil];
}
@end
